﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using orienta.Models;
using System.Text;
using Servicios.DataContract;
using System.Data;
using System.Security.Cryptography;
using System.Data.SqlClient;
using System.Collections;

namespace orienta.Controllers
{
    public class AccountController : Controller
    {

        private GoodTireEntities db = new GoodTireEntities();
        public int _TIPO_DOC_DNI = 1;
        public int _COD_USUARIO_ADMIN = 1;
        public int _Area = 0;

        //
        // GET: /Account/LogOn

        public ActionResult LogOn()
        {
            //return RedirectToAction( "Index","Home");
            return View();
        }

        //
        // POST: /Account/LogOn

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                //if (Membership.ValidateUser(model.UserName, model.UserName))
                if (Validar(model))
                {
                    return RedirectToAction("Index", "Bandeja");
                }
                else
                {
                   // ModelState.AddModelError("", "The user name or password provided is incorrect.");
                    //return RedirectToAction("Index", "Home");
            //        return View("Index", "Home", model);
                    return View(model);

                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/LogOff

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }

        //
        // GET: /Account/Register

        public ActionResult Register()
        {
            return View();
        }

        private Boolean Validar(LogOnModel model)
        {
            
            if (ModelState.IsValid)
            {
                try
                {
                    if (ValidarUserWs(model.UserName, model.Password))
                  // if(true)
                    {
                        ORIMaeUsuario usuario = db.ORIMaeUsuario.Single(o => o.vCodUsuario.Equals(model.UserName));
                        ORIMaeDependencia area = db.ORIMaeDependencia.Single(o => o.nIdeDep == usuario.nIdeDep);
                        String sUsuario = model.UserName + "@" + usuario.nIdeUsu + "@" + usuario.nIdeDep + "@" + area.vDescripcion + "@" + usuario.nIdeFuncionario + "@" + area.nIdeDepRegion;
                        FormsAuthentication.SetAuthCookie(sUsuario, false /* createPersistentCookie */);

                        ViewBag.MENU_ITEMS = Menu_ItemsQUEMADO;
                        return true;

                    }
                    else {
                        return false;
                    }

                    

                }
                catch (Exception e)
                {
                    String a = e.ToString();
                    Response.Write( a);
                    return false;
                }

            }
            else
                return false;
        }


        private Boolean ValidarUserWs(String user, String password)
        {


            try {


                ServicesClient objWC_ADMIN = new ServicesClient();

                Servicios.DataContract.DCUsuario objDCUsuario = new Servicios.DataContract.DCUsuario();
                List<Servicios.DataContract.DCUsuario> objListDCUsuario = new List<Servicios.DataContract.DCUsuario>();

                DCUsuario[] objArrayDCUsuario = new DCUsuario[50];


                objDCUsuario.Login = user;// "usr_orienta";
                objDCUsuario.Password = Encriptar(password);// "3fad33825b048c71f7d39a0860da7efd94177f78";
                objDCUsuario.UsuarioSistema = "USR_ORIENTA";
                objDCUsuario.PassSistema = "515T3M40R13NT4";


                objArrayDCUsuario = objWC_ADMIN.paADMIN_Validar_Usuario(objDCUsuario);

                if (objArrayDCUsuario == null || objArrayDCUsuario.Length==0)
                {
                    ModelState.AddModelError("", "Usuario y/o password incorrecto");
                    return false;
                }
                else {


                    ViewBag.MENU_ITEMS = Menu_ItemsWS(objArrayDCUsuario);
                    //ViewBag.MENU_ITEMS = Menu_ItemsQUEMADO;

                    guardarUsuarioDB(objArrayDCUsuario);
                    
                    return true;
                }


            
            }
            catch (Exception e)
            {
                String mensaje = e.ToString();
                String fuente = e.Source;
                if (fuente == "System.Data.Entity")
                {
                    if (mensaje.IndexOf("FK_ORIMaeDependencia_ORIMaeUsuario") > -1)
                        ModelState.AddModelError("", "El codigo de area: " + _Area + ", que tiene asignado el usuario, no existe en el sistema.");
                    else
                        ModelState.AddModelError("", "Error en la base de datos");

                }else
                    ModelState.AddModelError("", "El Webservice no se encuentra disponible");

                return false;
            }
        }


        private void guardarUsuarioDB(DCUsuario[] objArrayDCUsuario)
        {


            foreach (DCUsuario objrow in objArrayDCUsuario)
            {
                ORIMaeFuncionario objORIMaeFuncionario = new ORIMaeFuncionario();
                String[] nombe = objrow.Nombre.Split(' ');
                objORIMaeFuncionario.nIdeTipoDoc = _TIPO_DOC_DNI;
                objORIMaeFuncionario.vNumDocum = objrow.Dni;
                if(nombe.Length>0)
                    objORIMaeFuncionario.vPrimNombre = nombe[0];
                if (nombe.Length > 1)
                    objORIMaeFuncionario.vPrimApellido = nombe[1];
                if (nombe.Length > 2)
                    objORIMaeFuncionario.vSegApellido = nombe[2];
                else
                    objORIMaeFuncionario.vSegApellido = "";
                objORIMaeFuncionario.dFecReg = DateTime.Now;
                objORIMaeFuncionario.nIdeUsuReg = _COD_USUARIO_ADMIN;

                ORIMaeFuncionario objORIMaeFuncionarioDB = db.ORIMaeFuncionario.SingleOrDefault(o => (o.nIdeTipoDoc == _TIPO_DOC_DNI && o.vNumDocum == objrow.Dni));
                if (objORIMaeFuncionarioDB == null)
                {
                    db.ORIMaeFuncionario.AddObject(objORIMaeFuncionario);
                    db.SaveChanges();

                    objORIMaeFuncionarioDB = db.ORIMaeFuncionario.SingleOrDefault(o => (o.nIdeTipoDoc == _TIPO_DOC_DNI && o.vNumDocum == objrow.Dni));
                }
                else
                {
                    db.ObjectStateManager.ChangeObjectState(objORIMaeFuncionarioDB, EntityState.Detached);

                    objORIMaeFuncionarioDB.vPrimNombre = objORIMaeFuncionario.vPrimNombre;
                    objORIMaeFuncionarioDB.vPrimApellido = objORIMaeFuncionario.vPrimApellido;
                    objORIMaeFuncionarioDB.vSegApellido = objORIMaeFuncionario.vSegApellido;

                    db.ORIMaeFuncionario.Attach(objORIMaeFuncionarioDB);
                    db.ObjectStateManager.ChangeObjectState(objORIMaeFuncionarioDB, EntityState.Modified);
                    db.SaveChanges();
                }

                ORIMaeUsuario objORIMaeUsuario = new ORIMaeUsuario();
                objORIMaeUsuario.vCodUsuario = objrow.Login;
                objORIMaeUsuario.nIdePerfil = objrow.Id_Perfil;
                objORIMaeUsuario.nIdeDep = objrow.Id_Area;
                objORIMaeUsuario.nIdeFuncionario = objORIMaeFuncionarioDB.nIdeFuncionario;
                objORIMaeUsuario.dtFecReg = DateTime.Now;
                _Area = objrow.Id_Area;
                ORIMaeUsuario objORIMaeUsuarioDB = db.ORIMaeUsuario.SingleOrDefault(o => o.vCodUsuario == objORIMaeUsuario.vCodUsuario);

                if (objORIMaeUsuarioDB == null)
                {
                    db.ORIMaeUsuario.AddObject(objORIMaeUsuario);
                    db.SaveChanges();
                }
                else
                {
                    db.ORIMaeUsuario.Attach(objORIMaeUsuarioDB);
                    db.ObjectStateManager.ChangeObjectState(objORIMaeUsuarioDB, EntityState.Modified);
                    db.SaveChanges();
                }




            }
        
        }

        //
        // POST: /Account/Register

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus;
                Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
                    //ViewBag.Menu_Items = Menu_Items;
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePassword

        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        //
        // POST: /Account/ChangePassword

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {

                // ChangePassword will throw an exception rather
                // than return false in certain failure scenarios.
                bool changePasswordSucceeded;
                try
                {
                    MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
                    
                    changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePasswordSuccess

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        private HtmlString Menu_ItemsWS(DCUsuario[] opciones) {
            String url = Url.Content("~/");
            Hashtable menu = new Hashtable();


            StringBuilder menucito = new StringBuilder("var MENU_ITEMS =[");

            foreach (DCUsuario opcion in opciones) {

                ItemMenu item = new ItemMenu();
                item.subMenu = opcion.Des_Sub_Menu;
                item.pagina = opcion.Pagina;

                if (!menu.Contains(opcion.Des_menu))
                {
                    List<ItemMenu> items = new List<ItemMenu>();
                    items.Add(item);
                    menu.Add(opcion.Des_menu, items);
                }
                else
                {
                    List<ItemMenu> items = (List<ItemMenu>)menu[opcion.Des_menu];
                    items.Add(item);
                    menu[opcion.Des_menu] = items;
                }
            }

            foreach (DictionaryEntry entry in menu)
            {
                menucito.Append("['").Append(entry.Key).Append("',null, null,");
                List<ItemMenu> items = (List<ItemMenu>)entry.Value;
                foreach (ItemMenu item in items)
                {
                    menucito.Append("['").Append(item.subMenu).Append("','").Append(url).Append(item.pagina).Append("', null,],");
                }
                menucito.Append("],");
            }
            /*
            foreach (DCUsuario item in opciones)
            {
                menucito.Append("['").Append(item.Des_menu).Append("',null, null,");
                menucito.Append("['").Append(item.Des_Sub_Menu).Append("','").Append(url).Append(item.Pagina).Append("', null,],");
//                menucito.Append("['Busqueda Avanzada','").Append(url).Append("Busqueda', null,],");
                menucito.Append("],");

            }
             * /
            /*
            foreach (DCUsuario item in opciones) {
                menucito.Append("['Reportes',null, null,");
                menucito.Append("['Trazabilidad','").Append(url).Append("Trazabilidad', null,],");
                menucito.Append("['Busqueda Avanzada','").Append(url).Append("Busqueda', null,],");
                menucito.Append("],");

            }*/
            menucito.Append("];");
            
           var menu_items = new HtmlString(string.Format("<script>{0}</script>", menucito));
            System.Web.HttpContext.Current.Session["MENU_ITEMS"] = menu_items;
            return (HtmlString)menu_items;
        }

        

        protected HtmlString Menu_ItemsQUEMADO
        {
            get
            {

                String url = Url.Content("~/");

                StringBuilder menucito = new StringBuilder("var MENU_ITEMS =[");
                menucito.Append("['Reportes',null, null,");
                menucito.Append("['Trazabilidad','").Append(url).Append("Trazabilidad', null,],");
                menucito.Append("['Busqueda Avanzada','").Append(url).Append("Busqueda', null,],");
                menucito.Append("['Alertas','").Append(url).Append("Alertas', null,],");
                menucito.Append("],");
                menucito.Append("['Mantenimiento',null, null,");
                menucito.Append("['Catalogos','").Append(url).Append("CompendioDetalle/', null,],");
                menucito.Append("['Dependencias','").Append(url).Append("Dependencias/Create', null,],");
                menucito.Append("['Bandeja Usuario','").Append(url).Append("Funcionario/newFuncionarioCab', null,],");
                menucito.Append("],");
                menucito.Append("['Estadisticas','").Append(url).Append("Estadistica/Inicio', null,],");
                menucito.Append("['Bandeja','").Append(url).Append("Bandeja', null,");
                menucito.Append("['Entrada', '").Append(url).Append("Bandeja', null,],");
                menucito.Append("['Salida', '").Append(url).Append("Bandeja?tipo=S', null,],");
                menucito.Append("['Temporales', '").Append(url).Append("Bandeja?tipo=T', null,],");
                menucito.Append("],");
                menucito.Append("['Nueva Solicitud','").Append(url).Append("Solicitud', null,],];");

                var menu_items = System.Web.HttpContext.Current.Session["MENU_ITEMS"];

                if (menu_items == null)
                {
                    menu_items = new HtmlString(string.Format("<script>{0}</script>", menucito));
                    System.Web.HttpContext.Current.Session["MENU_ITEMS"] = menu_items;
                    return (HtmlString)menu_items;
                }
                return (HtmlString)menu_items;
            }

        }

        protected HtmlString Menu_Items111
        {
            get
            {
                StringBuilder menucito = new StringBuilder("var MENU_ITEMS =[['Solicitud', null, null,");
                menucito.Append("['Nueva solicitud', '/Solicitud/Index', null,],");
                menucito.Append("],");
                menucito.Append("['Bandeja','/Bandeja/Index', null,");
                menucito.Append("['Entrada', '/Bandeja/Index', null,],");
                menucito.Append("['Salida', '/Bandeja?tipo=S', null,],");
                menucito.Append("['Temporales', '/Bandeja?tipo=T', null,],");
                menucito.Append("],");
                menucito.Append("['Catalogos','/Compendio/', null,],");
                menucito.Append("['Trazabilidad','/Trazabilidad', null,],");

                menucito.Append("['Mantenimientos','/Mantenimientos/', null,");
                menucito.Append("['Personas', '/MaePersonas/Create', null,],");
                menucito.Append("['Dependencias', '/Dependencias/Create', null,],");
                menucito.Append("],");

                menucito.Append("['Estadisticas','/Estadistica/Inicio', null,],];");

               

                var menu_items = System.Web.HttpContext.Current.Session["MENU_ITEMS"];

                if (menu_items == null)
                {
                    menu_items = new HtmlString(string.Format("<script>{0}</script>", menucito));
                    System.Web.HttpContext.Current.Session["MENU_ITEMS"] = menu_items;
                    return (HtmlString)menu_items;
                }
                return (HtmlString)menu_items;
            }


        
        }

        private class ItemMenu {

            public String subMenu { get; set; }
            public String pagina{ get; set; }
        }
        public string Encriptar(string str)
        {
            SHA1 sha1 = SHA1Managed.Create();
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] stream = null;
            StringBuilder sb = new StringBuilder();
            stream = sha1.ComputeHash(encoding.GetBytes(str));
            for (int i = 0; i < stream.Length; i++) sb.AppendFormat("{0:x2}", stream[i]);
            return sb.ToString();
        }
        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }
}
